package com.bfdx.testkeyevent

import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.bfdx.testkeyevent.service.KeyEventService
import com.bfdx.testkeyevent.ui.compose.DialogState
import com.bfdx.testkeyevent.ui.compose.MsgDialog
import com.bfdx.testkeyevent.ui.compose.rememberDialogState
import com.bfdx.testkeyevent.ui.theme.TestKeyEventTheme
import com.orhanobut.logger.Logger
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class ServiceActivity : ComponentActivity() {

    private val keyLogList = mutableStateListOf<KeyLog>()

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onKeyLog(log: KeyLog) {
        keyLogList.add(log)
    }

    private var keyServiceDialog: DialogState? = null

    @Composable
    private fun KeyServiceDialog(
        dialog: DialogState,
        context: Context,
    ) {
        MsgDialog(
            dialogState = dialog,
            title = "按键服务未启用",
            text = "按[确定]转到[按键配置]页面，启用[TestKeyEvent按键服务]",
            onPositive = { goToAccessibilitySetting(context) },
            onDismiss = { },
            content = {},
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TestKeyEventTheme {
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
                    val scope = rememberCoroutineScope()
                    val scrollState: LazyListState = rememberLazyListState()
                    LaunchedEffect(keyLogList.size) {
                        scope.launch {
                            scrollState.animateScrollToItem(scrollState.layoutInfo.lastIndex)
                        }
                        if (keyLogList.isNotEmpty()) Logger.i(keyLogStr)
                    }
                    val dialog = rememberDialogState()
                    keyServiceDialog = dialog
                    KeyServiceDialog(dialog = dialog, this)
                    Column(
                        modifier = Modifier.fillMaxSize()
                    ) {
                        Button(
                            modifier = Modifier.fillMaxWidth(),
                            onClick = { goToAccessibilitySetting(this@ServiceActivity) }) {
                            Text(text = "去启用按键服务")
                        }
                        Button(
                            modifier = Modifier.fillMaxWidth(),
                            onClick = { keyLogList.clear() }) {
                            Text(text = "清空")
                        }
                        LazyColumn(
                            modifier = Modifier.fillMaxWidth(),
                            state = scrollState,
                            verticalArrangement = Arrangement.Top,
                            horizontalAlignment = Alignment.CenterHorizontally,
                        ) {
                            keyLogList.forEachIndexed { index, keyLog ->
                                item {
                                    Text(text = "${index + 1}. ${formatKeyLog(keyLog)}")
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (event?.keyCode) {
            null -> return super.onKeyDown(keyCode, event)
            KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN -> return super.onKeyDown(keyCode, event)
            else -> checkKeyService(this)
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun checkKeyService(context: Context) {
        val enabled = isAccessibilityEnabled(context, KeyEventService::class.java.name)
        if (!enabled && keyServiceDialog?.showing != true) {
            keyServiceDialog?.show()
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    private val keyLogStr: String
        get() = keyLogList.mapIndexed { index, keyLog -> Pair(index, keyLog) }
            .joinToString(separator = "\n") { "${it.first + 1}. ${formatKeyLog(it.second)}" }

}